<template>
  <n-modal
    :show="showModal"
    preset="dialog"
    :title="title"
    :closable="false"
    positive-text="确认"
    negative-text="取消"
    @positive-click="submitCallback"
    @negative-click="close"
    @on-update:show="close"
  >
    <n-form ref="formRef" :model="formData" :rules="rules">
      <n-form-item v-if="type !== 'password'" label="账号">
        <n-input v-model:value="formData.username" />
      </n-form-item>
      <n-form-item v-if="type !== 'password'" label="用户名">
        <n-input v-model:value="formData.nickname" />
      </n-form-item>
      <div v-if="type !== 'edit'">
        <n-form-item label="密码">
          <n-input
            v-model:value="formData.password"
            type="password"
            show-password-on="mousedown"
          />
        </n-form-item>
        <n-form-item label="确认密码">
          <n-input
            v-model:value="formData.confirm"
            type="password"
            show-password-on="mousedown"
          />
        </n-form-item>
      </div>
      <n-form-item v-if="type !== 'password'" label="部门">
        <n-tree-select
          v-model:value="formData.depts"
          multiple
          :options="deptOptions"
          key-field="id"
          label-field="name"
        />
      </n-form-item>
    </n-form>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import type { UserModel } from "@/api/user/model";
import type { UserFormParams } from "@/api/user/type";
import { NModal, NForm, NFormItem, NInput, NTreeSelect } from "naive-ui";
import type { TreeSelectOption, FormInst } from "naive-ui";
import { editUser, createUser, resetPassword } from "@/api/user";
import { getTeamList } from "@/api/team";
import { message } from "@/utils/message";

const props = defineProps<{
  showModal: boolean;
  currentUser: UserModel;
  type: "add" | "edit" | "password";
}>();

const emit = defineEmits<{
  (event: "update:showModal", value: boolean): void;
  (event: "submitCallback"): void;
}>();

const title = computed(() => {
  return props.type === "add"
    ? "新建用户"
    : props.type === "edit"
      ? "编辑用户"
      : "重置密码";
});

const deptOptions = ref<TreeSelectOption[]>([]);
const formRef = ref<FormInst | null>(null);
const formData = ref<UserFormParams>({
  username: "",
  nickname: "",
  password: "",
  confirm: "",
  depts: [],
});

const rules = {
  name: {
    required: true,
    message: "请输入用户名",
  },
  password: {
    required: true,
    message: "请输入密码",
  },
  confirmPassword: {
    required: true,
    message: "请输入确认密码",
  },
  depts: {
    required: true,
    message: "请输入部门",
  },
};

const submitCallback = async () => {
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      return;
    }

    if (props.type === "edit") {
      const res = await editUser(props.currentUser.id!, {
        username: formData.value.username,
        nickname: formData.value.nickname,
        depts: formData.value.depts,
      });
      if (res.code !== 200) {
        message.error(res.message);
      }
    } else if (props.type === "add") {
      const res = await createUser(formData.value);
      if (res.code !== 200) {
        message.error(res.message);
      }
    } else {
      const res = await resetPassword({
        id: props.currentUser.id!,
        password: formData.value.password!,
        confirm: formData.value.confirm!,
      });
      if (res.code !== 200) {
        message.error(res.message);
      }
    }
    close();
    emit("submitCallback");
  });
};

const close = () => {
  emit("update:showModal", false);
};

const initDeptOptions = async () => {
  const res = await getTeamList();
  if (res.code === 200) {
    deptOptions.value = res.data;
  }
};

onMounted(() => {
  initDeptOptions();
});

watch(
  () => props.currentUser,
  (newVal) => {
    if (newVal) {
      formData.value = {
        username: newVal.username,
        nickname: newVal.nickname,
      };
    }
  },
  { immediate: true },
);
</script>
